package com.xiaoyu.lanling.wxapi

import `in`.srain.cube.util.CLog
import android.content.Intent
import android.os.Build
import android.os.Bundle
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.xiaoyu.base.AppConfig
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.pay.WE_CHAT_PAY
import com.xiaoyu.pay.event.PayEvent

open class WXPayEntryActivity : AppCompatToolbarActivity(), IWXAPIEventHandler {

    private var mIWXAPI: IWXAPI? = null

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        mIWXAPI = WXAPIFactory.createWXAPI(AppContext.getContext(), AppConfig.wechatAppId(), true)
        mIWXAPI?.handleIntent(intent, this)
    }

    override fun onResumeSafelyAfterAppFinishInit(isFirstTimeResume: Boolean) {}
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        mIWXAPI?.handleIntent(intent, this)
    }

    override fun onDestroy() {
        super.onDestroy()
        mIWXAPI?.unregisterApp()
        mIWXAPI?.detach()
        mIWXAPI = null
    }

    override fun isSetRequestedOrientationPortrait(): Boolean {
        return Build.VERSION.SDK_INT != Build.VERSION_CODES.O
    }

    override fun onReq(baseReq: BaseReq) {}

    override fun onResp(baseResp: BaseResp) {
        if (baseResp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {  // pay
            var isSuccess = false
            when (baseResp.errCode) {
                BaseResp.ErrCode.ERR_OK -> {
                    isSuccess = true
                    CLog.i("WeChatPay", "订单支付成功")
                }
                BaseResp.ErrCode.ERR_COMM -> {
                    CLog.i("WeChatPay", "订单支付失败: -1")
                    logForWeChatPayFail(BaseResp.ErrCode.ERR_COMM)
                }
                BaseResp.ErrCode.ERR_USER_CANCEL -> {
                    CLog.i("WeChatPay", "订单支付失败: 用户取消")
                    logForWeChatPayFail(BaseResp.ErrCode.ERR_USER_CANCEL)
                }
                else -> {
                    CLog.i("WeChatPay", "订单支付失败: " + baseResp.errCode)
                    logForWeChatPayFail(BaseResp.ErrCode.ERR_AUTH_DENIED)
                }
            }
            PayEvent(WE_CHAT_PAY, isSuccess, baseResp.errCode.toString()).post()
        }
        finish()
    }

    private fun logForWeChatPayFail(statusCode: Int) {
        val params = Bundle()
        params.putString("status_code", statusCode.toString())
        //        UTUtil.getInstance().logEvent("vip_buy_failed", params);
    }
}